
#include <stdio.h>
#include <QMessageBox>

#include "Agence.h"
#include "Relation.h"
#include "TrueLoveClient.h"
#include "StatistiquesAgence.h"

StatistiquesAgence::StatistiquesAgence(QWidget *parent)
: QMainWindow(parent), Ui_StatistiquesAgence()
{
	setupUi(this);

	Agence a = Agence::Get();
	QList<TrueLoveClient> clients = TrueLoveClient::GetClients();
	relationsTmp = Relation::GetRelations();;

	lcdNumberTotal->display(a.GetNbRendezVousTotal());
	lcdNumberReussis->display(a.GetNbRendezVousSucces());	

	for(int i=0; i<relationsTmp.size(); i++)
	{
		Relation r = relationsTmp.at(i);
		TrueLoveClient c1 = TrueLoveClient::FindClientById(clients, r.GetId1());
		TrueLoveClient c2 = TrueLoveClient::FindClientById(clients, r.GetId2());
		listWidgetRelations->addItem(QString("%1 %2 & %3 %4")
			.arg(c1.GetPrenom()).arg(c1.GetNom())
			.arg(c2.GetPrenom()).arg(c2.GetNom()));
	}

	lastIdx = 0;

	Relation r = relationsTmp.at(lastIdx);
	checkBoxMarried->setChecked(r.IsMarried());
	textEditBebes->clear();
		
	if(r.GetBebes().size() > 0)	
		for(int i=0; i<r.GetBebes().size(); i++)
			textEditBebes->append(QString("%1,").arg(r.GetBebes().at(i)));

}

void StatistiquesAgence::ShowConfirmChangesDialog()
{
	int r = QMessageBox::information(this, tr("TrueLove | Information:"), 
		"<i>Les changements que vous aurez effectu&eacute; seront pris en compte. Voulez-vous enregistrer les changements?</i>", 
		QMessageBox::Save|QMessageBox::Discard|QMessageBox::Cancel);
	if (r == QMessageBox::Save) 
		accept();
	else if (r == QMessageBox::Discard) 
		retourAccueil();
}

void StatistiquesAgence::accept()
{
	Relation::SaveRelations(relationsTmp);	
	retourAccueil();
}

void StatistiquesAgence::retourAccueil()
{
	deleteLater();
	parentWidget()->show();
}

void StatistiquesAgence::closeEvent(QCloseEvent* event)
{
	retourAccueil();
}

void StatistiquesAgence::SaveCurrentRelation()
{
	Relation r = relationsTmp.at(lastIdx);
	r.SetMarried(checkBoxMarried->isChecked());
	QStringList listBebes = textEditBebes->toPlainText().trimmed().split(",");
	r.MangeTousLesBebes();

	for(int i=0; i<listBebes.size(); i++)
		if(listBebes.at(i).trimmed() != "")
			r.AddBebe(listBebes.at(i).trimmed());

	relationsTmp.replace(lastIdx, r);
}

void StatistiquesAgence::EnableDisable(int idx)
{
	SaveCurrentRelation();
	if(idx >= 0)
	{
		Relation r = relationsTmp.at(idx);
		checkBoxMarried->setEnabled(true);
		checkBoxMarried->setChecked(r.IsMarried());
		textEditBebes->setEnabled(true);
		textEditBebes->clear();
		
		if(r.GetBebes().size() > 0)	
			for(int i=0; i<r.GetBebes().size(); i++)
				textEditBebes->append(QString("%1,").arg(r.GetBebes().at(i)));
	}
	else
	{
		checkBoxMarried->setEnabled(false);
		textEditBebes->setEnabled(false);
	}

	lastIdx = idx;
}

void StatistiquesAgence::updateRelations()
{
	SaveCurrentRelation();
	ShowConfirmChangesDialog();
}

